import { app, shell, BrowserWindow,ipcMain,Tray, Menu, nativeTheme ,nativeImage } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'

// import { autoUpdater } from 'electron-updater';

let mainWindow;
function createWindow(): void {
  // Create the browser window.
   mainWindow = new BrowserWindow({
    // width: 900,
    // height: 670,
    // show: false,
    // frame: false,
    // transparent: true,
    // autoHideMenuBar: true,
    // ...(process.platform === 'linux' ? { icon } : {}),
    icon: join(__dirname, '../../resources/kyvision.ico'),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    },
    title: '网络管理客户端'
  })
  nativeTheme.themeSource = 'dark';
  mainWindow.on('ready-to-show', () => {
    mainWindow.maximize()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
 
}
//隐藏菜单
// Menu.setApplicationMenu(null)
//自动更新
// const checkAppVersionUpdate = () => {
// 	// 应用退出后自动安装
// 	autoUpdater.autoInstallOnAppQuit = true;
// 	// 自动下载
// 	autoUpdater.autoDownload = true;
// 	// 检测是否有更新包并通知
// 	autoUpdater.checkForUpdatesAndNotify().catch();
	
// 	// 下载进度
// 	autoUpdater.on('download-progress', (prog) => {
// 		mainWindow.webContents.send('app-update-version', {
// 			speed: Math.ceil(prog.bytesPerSecond / 1000), // 网速
// 			percent: Math.ceil(prog.percent) // 百分比
// 		})
// 	})
	
// 	// 安装最新版本
// 	autoUpdater.on('update-downloaded', (info) => {
// 		let dialogOpts = {
// 			type: 'info',
// 			buttons: ['重新启动', '取消'],
// 			title: '应用程序更新',
// 			message: '已下载新版本。重新启动应用程序以安装最新版本',
// 			detail: info.releaseNotes
// 		}
// 		dialog.showMessageBox(dialogOpts).then(result => {
// 			if(result.response == 0) autoUpdater.quitAndInstall();
// 		})
// 	})
// }

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  createWindow()
  //托盘菜单
  trayMenu()
  //顶部菜单
  topMenu()


  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
  
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
//单例运行
const getTheLock=app.requestSingleInstanceLock()
if(!getTheLock){
  app.quit()
}

//注册协议
app.setAsDefaultProtocolClient("dog-clock")
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
function trayMenu():void{
   //托盘菜单
   let tray = new Tray(nativeImage.createFromPath(join(__dirname, '../../resources/kyvision.ico')));
   let contextMenu = Menu.buildFromTemplate([
       {
           label: '意见反馈',
           click: () => console.log('点击了意见反馈')
       },
       {
           label: '帮助中心',
           click: () => console.log('点击了帮助中心')
       },
       {
           label: '更新检测',
           click: () => console.log('点击了更新检测')
       },
       {
           label: '退出',
           // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
           click: () => console.log('点击了退出')
       }
   ])
    
   tray.setToolTip('广东彭于晏之深圳分晏'); // 鼠标悬停托盘系统图标显示
   tray.setContextMenu(contextMenu);
    
   tray.on('click', () => mainWindow.show()); // 单机托盘图标打开应用程序
}


//锁定客户端
// function clientLock(time):void{

// }

function topMenu():void{
   // 定义菜单模板
   const template:Electron.MenuItemConstructorOptions[] = [
    {
      label: '系统',
      submenu: [
        {
          label: '锁定客户端',
          click: () => {
            console.log('锁定客户端');
          },
        },
        {
          label: '自动锁定设置',
          click: () => {
            console.log('自动锁定设置');
          },
        },
        {
          type: 'separator',
        },
        {
          label: '退出',
          click: () => {
            app.quit();
          },
        },
      ],
    },
    {
      label: '配置',
      submenu: [
        { label: '子网管理',
          click:()=>{
              console.log("子网管理")
          }
         },
         { label: '子网权限管理',
          click:()=>{
              console.log("子网权限管理")
          }
         },
        { type: 'separator' },
        { label: '告警通知配置',
          click:()=>{
              console.log("告警通知配置")
          }
         },
         { label: '设备属性配置',
          click:()=>{
              console.log("设备属性配置")
          }
         },
         { label: '拓扑视图配置',
          click:()=>{
              console.log("拓扑视图配置")
          }
         },
         { label: '下联装置配置',
          click:()=>{
              console.log("下联装置配置")
          }
         },
      ],
    },
    {
      label: '故障',
      submenu: [
        { label: '活动告警列表',
          click:()=>{
              console.log("活动告警列表")
          }
         },
         { label: '告警铃音',
          click:()=>{
              console.log("下联装置配置")
          }
         },
         { label: '操作日志',
          click:()=>{
              console.log("操作日志")
          }
         },
         { label: '运行日志',
          click:()=>{
              console.log("运行日志")
          }
         },
         { label: 'SysLog',
          click:()=>{
              console.log("SysLog")
          }
         },
      ],
    },
    {
      label: '安全',
      submenu: [
        { label: 'EMS用户',
          click:()=>{
              console.log("EMS用户")
          }
         },
      ],
    },
    {
      label: '报表',
      submenu: [
        {
          label: '故障管理',
          click: () => {
            console.log("故障管理")
          },
        },
        {
          label: '实时性能',
          click: () => {
            console.log("实时性能")
          },
        },
        {
          label: '光功率图',
          click: () => {
            console.log("光功率图")
          },
        },
        {
          label: '光功率表',
          click: () => {
            console.log("光功率表")
          },
        },
      ],
    },
    {
      label: '维护',
      submenu: [
        {
          label: 'FTP服务器配置',
          click: () => {
            console.log("FTP服务器配置")
          },
        },
        {
          label: '设备配置导出',
          click: () => {
            console.log("设备配置导出")
          },
        },
        {
          label: '设备配置导入',
          click: () => {
            console.log("设备配置导入")
          },
        },
        {
          label: '设备软件升级',
          click: () => {
            console.log("设备软件升级")
          },
        },
        {
          label: '网管数据备份',
          click: () => {
            console.log("网管数据备份")
          },
        },
        {
          label: '网管数据恢复',
          click: () => {
            console.log("网管数据恢复")
          },
        },
        {
          label: '网管数据清理',
          click: () => {
            console.log("网管数据清理")
          },
        },
      ],
    },
    {
      label: '窗体',
      submenu: [
        {
          label: '显示设备IP',
          click: () => {
            console.log("显示设备IP")
          },
        },
        {
          label: '层叠窗口',
          click: () => {
            console.log("层叠窗口")
          },
        },
        {
          label: '排列窗口',
          click: () => {
            console.log("排列窗口")
          },
        }
      ],
    },
    {
      label: '帮助',
      role:'help',
      submenu: [
        {
          label: '关于',
          click: () => {
            console.log("关于")
          },
        },
        {
          label: 'SNMP-JManager',
          click: () => {
            console.log("JManager")
          },
        },
      ],
    },
  ];

  // 创建菜单
  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);
}